from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
import random
import re

from rest_framework.response import Response
from apps.users.serializers import UserRegSerializer

#获取验证码
# class SmsCodeView(APIView):
#     def get(self, request, mobile):
#
#         if not re.match(r'^1[345789]\d{9}$', mobile):
#             return Response({'success': False, 'message': '手机有误'})
#
#         if not re.match(r'^1[345789]\d{9}$', mobile):
#             return Response({'success': False, 'message': '手机有误'})
#         sms_code = "%06d" % random.randint(0, 999999)
#         # sms_code = randint(100000, 999999)
#         print(sms_code)
#         # 存到数据库
#         sms_redis_client = get_redis_connection('verifications')
#
#         # 通过标识判断是否发送频繁
#         send_flag = sms_redis_client.get('send_flag_%s' % mobile)
#         if send_flag:
#             return Response({'success': False, 'message': '发送频繁，请稍后再试'})
#
#         # 1.实例化管道
#         pipeline = sms_redis_client.pipeline()
#         # 2.将任务添加管道
#         pipeline.setex('send_flag_%s' % mobile, 60, 1)
#         pipeline.setex("sms_%s" % mobile, 300, sms_code)
#         # 3.实行管道'
#         pipeline.execute()
#         return Response({'success': True, 'sms_code': sms_code, 'message': 'OK'})
from random import randint
class SmsCodeView(APIView):
    def get(self, request, mobile):
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return Response({'success': False, 'message': '手机号输入不正确'})
        # count = User.objects.filter(mobile=mobile).count()
        # if count != 0:
        #     return Response({'success': False, 'message': '手机号已被使用'})
        sms_code = "%06d" % randint(0, 999999)
        # 存到数据库
        redis_conn = get_redis_connection('verifications')

        # 通过标识判断是否发送频繁
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'success': False, 'message': '发送频繁，请稍后再试'})

        # 1.实例化管道
        pipeline = redis_conn.pipeline()
        # 2.将任务添加管道
        pipeline.setex('send_flag_%s' % mobile, 60, 1)
        pipeline.setex("sms_%s" % mobile, 300, sms_code)
        # 3.实行管道'
        pipeline.execute()
        return Response({'success': True, 'sms_code': sms_code, 'message': 'OK'})
#完成注册逻辑
from rest_framework import status
class UserRegView(CreateAPIView):
    serializer_class = UserRegSerializer
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

